import React, {Component} from 'react'
import {Link, history} from 'react-router'
import $ from 'jquery'
import {R_header_fixed} from './common/index'
import {Toast, HttpService} from '../Http'
//import WxServer from '../wx/WxServer'

import imgCard1 from '../img/card/1.png'
import imgCard2 from '../img/card/2.png'
import imgCard3 from '../img/card/3.png'
import Popup from './common/popup'
import select from '../img/pay/select.png'
import unselect from '../img/pay/unselect.png'
import weixin from '../img/weixin.png'
import alipay from '../img/alipay.png'
import success from '../img/pay/success.png'
import fail from '../img/pay/fail.png'
export default class BuyDevice extends Component {
    constructor(props) {
        super(props);
        this.state = {
            first: 1,
            second: 0,
            third: 0,
            total: 0,
            address: '',
            phone: 0,
            recivername: '',
            isShow: false,
            type: 2,
            price:{
                smartwatch:'',
                whitecard13_56:'',
                whitecard:''
            }
        }

        this.config = {
            isSure: true,
            isCancel: false,
            tip: true,
            no: '我知道了',
            content: <div className="tipimg"><img  src={success} /><p>支付完成</p></div>,
            no_cb: () => {
                let len = window.history.length - localStorage.len + 1;
                window.history.go(-len);
            }
        };
    }


    componentWillMount() {

        var rec = this;
        if (location.href.indexOf("back") > 0) {
            HttpService.query({
                url: '/pay/getOrderStatus',
                sync: false,
                data: {
                    token: localStorage.appToken,
                    orderno: localStorage.orderno
                },
                success: (res => {
                    if(res.code=="0"){
                        if(res.data.tradestatus==2){
                            rec.config.content= <div className="tipimg"><img  src={success} /><p>支付成功!</p></div>
                        }else if(res.data.tradestatus==3){
                            rec.config.content= <div className="tipimg"><img  src={fail} /><p>支付失败!</p></div>
                        }

                    }
                })
            });
            rec.setState({
                isShow: true
            })
        } else {
            localStorage.len = window.history.length;
        }


        HttpService.query({
            url: '/app/user/getUserinfo',
            sync: true,
            data: {
                token: localStorage.appToken,
                babyid: localStorage.babyid
            },
            success: (res => {
                let address = '[无收货地址..]'
                if (res.data.deliveryaddr != null) {
                    address = res.data.province + res.data.city + res.data.town
                }
                this.setState({
                    address,
                    deliveryaddr: res.data.deliveryaddr || '',
                    phone: res.data.telephone,
                    recivername: res.data.recivername || '[无收货人]'
                })
            })
        });
        HttpService.query({
            url: '/app/device/getPrices',
            sync: false,
            data: {
                token: localStorage.appToken,
                schoolname:localStorage.schoolname
            },
            success: (res => {
                this.setState({
                    price:{
                        smartcard:res.data.smartcard,
                        whitecard13_56:res.data.whitecard13_56,
                        whitecard:res.data.whitecard
                    }
                })
                let pri=res.data;
                let price = this.state.first * pri.smartcard + this.state.second * pri.whitecard + this.state.third * pri.whitecard13_56
                this.setState({total: price.toFixed(2)})
            })
        });

    }


    /**
     * buydevice 是否有值--没有则默认
     * map页面加载完后--加载百度统计点击事件
     */
    componentDidMount() {
        const pri=this.state.price;
        let from = '购买设备';
        if (this.props.params.shengji == 'true')
            from += '<-升级设备';
        if (localStorage.buydevice) {
            const buydevice = localStorage.buydevice.split(',');
            if (this.props.params.shengji == 'true') {
                buydevice[1] = 0;
                buydevice[2] = 0;
            }
            const price = buydevice[0] * pri.smartcard + buydevice[1] * pri.whitecard + buydevice[2] * pri.whitecard13_56;
            this.setState({first: buydevice[0], second: buydevice[1], third: buydevice[2], total: price.toFixed(2)})
        }
        console.log(from);
        _hmt.push(['_trackEvent', 'page', 'buydevice', from]);
    }

    componentWillUnmount() {
        localStorage.buydevice = this.state.first + ',' + this.state.second + ',' + this.state.third;
    }

    totalPrice() {
        const pri=this.state.price;
        let price = this.state.first * pri.smartcard + this.state.second * pri.whitecard + this.state.third * pri.whitecard13_56
        this.setState({total: price.toFixed(2)})
    }

    numHandle(name, obj) {
        let data = {};
        if (obj.currentTarget.className == 'add') {
            data[name] = ++this.state[name];
        } else {
            if (this.state[name] == 0)
                return;
            data[name] = --this.state[name];
        }
        this.setState(data);
        this.totalPrice();
    }

    buySubmit(e) {
        var rec=this;
        const pri=this.state.price;
        e.preventDefault();
        // if (!/micromessenger/.test(navigator.userAgent.toLowerCase())) {
        //     Toast.toast('在微信端登录方可支付')
        //     return;
        // }
        if (this.state.recivername == '[无收货人]' || this.state.deliveryaddr == '') {
            Toast.toast('请完善收货地址信息');
            return;
        }
        if (this.state.total == 0) {
            Toast.toast('请至少选择一个设备');
            return;
        }
        let data = ''; //格式：设备类型(123),设备价格,数量|设备类型,设备价格,数量
        if (this.state.first > 0) {
            data += `2,${pri.smartcard},` + this.state.first + '|'
        }
        if (this.state.second > 0) {
            data += `3,${pri.whitecard},` + this.state.second + '|'
        }
        if (this.state.third > 0) {
            data += `13_56,${pri.whitecard13_56},` + this.state.third + '|'
        }
        let clkbuy = '立即购买';
        if (this.props.params.shengji == 'true') {
            clkbuy = '立即购买-升级';
        }
        //什么入口进入立即购买页面--添加百度统计点击事件
        _hmt.push(['_trackEvent', 'page', 'BuyDevice', clkbuy]);
        let type=this.state.type;
        let source,payType;
        if(type==1){
            source= 'WEIXIN_H5'

        }else{
            source= 'ALIPAY_H5'
        }
        HttpService.query({
            url: '/app/device/purchase',
            sync: false,
            data: {
                token: localStorage.appToken,
                babyid: localStorage.babyid,
                data: data.slice(0, -1),
                source: source,
                weixinclient: true
            },
            success: (res => {
                if (res.code == 10134) {
                    _hmt.push(['_trackEvent', 'page', 'buydevice', '购买设备[提交操作]']);
                    localStorage.orderno=res.data;
                    if(rec.state.type==1){
                        $.ajax({
                            url: '/wxpay/wxmweb/unified_order',
                            type: 'post',
                            data: {
                                token: localStorage.appToken,
                                orderno: res.data,
                                payType:source
                            },
                            success: function (res) {
                                 window.location.href=res.data;
                            },
                            error: function () {

                            }
                        });
                    }else{
                        $.ajax({
                            url: '/pay/getPay',
                            type: 'post',
                            data: {
                                token: localStorage.appToken,
                                orderno: res.data,
                                payType: 'ALIPAY_H5',
                                returnurl: location.href.split("#")[0] + '#/BuyDevice/back',
                                ordernotype:1
                            },
                            success: function (res) {
                                if (res.code == "0") {
                                    document.write(res.data)
                                } else {
                                    Toast.toast(res.msg);
                                }
                            },
                            error: function () {

                            }
                        });
                    }

                } else {
                    Toast.toast(res.msg);
                }
            })
        })

    }

    buysbmtno(e) {
        e.preventDefault();
    }

    select(type) {
        this.setState({type: type})
    };

    render() {
        const {
            first,
            second,
            third,
            total,
            address,
            phone,
            recivername,
            deliveryaddr,
            isShow,
            type,
            price
        } = this.state
        return (
            <form className='buybox' onSubmit={this.buysbmtno.bind(this)}>
                <R_header_fixed left="1" title="购买设备" />
                <Popup config={this.config} blockOrNone={isShow} _flag={isShow}/>
                <Link to={'/Address/' + this.props.params.shengji} className='buyinfo'>
                    <h5>收货人信息</h5>
                    <div className='aduser'>
                        <span>{recivername || ''}</span>
                        <span>{phone || ''}</span>
                    </div>
                    <p className='adcity'>{address + deliveryaddr}</p>
                    <span className='adstatus'>编辑</span>
                </Link>
                <ul className='buylist'>
                    <li>
                        <img src={imgCard3}/>
                        <h4>智能学生证</h4>
                        <h5>价格：{price.smartcard+".00"}</h5>
                        <div className='intro'>
                            <span >实时定位，亲情通话，宝宝更安全</span>
                            <p className='btns'>
                                <button className='del' onClick={this.numHandle.bind(this, 'first')}/>
                                <span>{first}</span>
                                <button className='add' onClick={this.numHandle.bind(this, 'first')}/>
                            </p>
                        </div>
                    </li>
                    {this.props.params.shengji == 'true'
                        ? ''
                        : <li>
                            <img src={imgCard1}/>

                            <h4>2.4G考勤卡</h4>
                            <h5>价格：{price.whitecard+".00"}</h5>
                            <div className='intro'>
                               <span>建议购买前咨询客服，确认孩子所在的学校所使用的考勤卡类型</span>
                                <p className='btns'>
                                    <button className='del' onClick={this.numHandle.bind(this, 'second')}/>
                                    <span>{second}</span>
                                    <button className='add' onClick={this.numHandle.bind(this, 'second')}/>
                                </p>
                            </div>
                        </li>}

                    {this.props.params.shengji == 'true'
                        ? ''
                        : <li>
                            <img src={imgCard2}/>
                            <h4>
                                13.56 G考勤卡
                            </h4>
                            <h5>价格：{price.whitecard13_56+".00"}</h5 >
                            <div className='intro'>
                                建议购买前咨询客服，确认孩子所在的学校所使用的考勤卡类型
                                <p className='btns'>
                                    <button className='del' onClick={this.numHandle.bind(this, 'third')}/>
                                    <span>{third}</span>
                                    <button className='add' onClick={this.numHandle.bind(this, 'third')}/>
                                </p>
                            </div>
                        </li>
                    }
                </ul>
                <div className="choosePay">
                    {/*<div className="title">请选择支付方式：</div>*/}
                    <ul className="type">
                        {/*<li className="step">*/}
                            {/*<img className="icon" src={weixin}/>*/}
                            {/*<div>微信支付</div>*/}
                            {/*<div className="app-img" onClick={this.select.bind(this, 1)}>*/}
                                {/*<img src={type == 1*/}
                                    {/*? select*/}
                                    {/*: unselect} className="app-all-img"/>*/}
                            {/*</div>*/}

                        {/*</li>*/}
                        <li className="step">
                             <img className="icon" src={alipay}/>
                              <div>支付宝支付</div>
                            <div className="app-img s-j-end" onClick={this.select.bind(this, 2)}>
                                <img src={type == 2
                                    ? select
                                    : unselect} className="app-all-img"/>
                            </div>

                        </li>
                    </ul>
                </div>
                {total == '0.00'
                    ? ''
                    : <div className='smtbox'>
                        总价：<span>{total}</span>
                        <button onClick={this.buySubmit.bind(this)} className="tgGoBal">去结算</button>
                    </div>}

            </form>
        )
    }
}
